package com.example.demo.command;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import ch.selise.exercise.pattern.notepad.command.CommandExecutor;
import ch.selise.exercise.pattern.notepad.command.GetCommandParameter;
import ch.selise.exercise.pattern.notepad.exception.EmptyStackException;
import ch.selise.exercise.pattern.notepad.exception.ExecuteException;
import ch.selise.exercise.pattern.notepad.exception.UnsupportedCommandException;
import ch.selise.exercise.pattern.notepad.storage.AppStorageSingleton;

import com.example.demo.views.DataEntryTable;
import com.vaadin.ui.AbstractField;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Table;

public class AddActionCommand extends ActionCommand {

	private static final long serialVersionUID = -7526300352008367414L;
	private AbstractField source = null;
	
	public AddActionCommand(String command, Table table) {
		super(command,table);
	}
	
	public AddActionCommand(String command, Table table, AbstractField field) {
		this(command,table);
		this.source = field;
	}

	@Override
	protected void postClickAction(ClickEvent event) {
		
		String text = "";
		
		if(getSource() != null){
			text = getSource().getValue().toString();
		}
		
		if (text.length() != 0) {
			CommandExecutor commandExecutor = CommandExecutor.getInstance();;
			try {
				commandExecutor.executeCommand(new GetCommandParameter(
						getCommand(), text, 0));
			} catch (ExecuteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (EmptyStackException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedCommandException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			finally{
				addTextToTable();
			}
		}
	}

	/**
	 * printing from storage.
	 */
	private void addTextToTable() {
		
		int index = AppStorageSingleton.getInstance().getText().size() - 1;
		String entry = AppStorageSingleton.getInstance().getText().get(index);
		Map<String, Object> x = new HashMap<String, Object>();
		x.put("Text", entry);
		x.put("Edit", "Edit");
		x.put("Delete", "Del");
		if(getTableX() instanceof DataEntryTable){
			
			List<Map<String, Object>> dataSet = new ArrayList<Map<String,Object>>();
			dataSet.add(x);
			Map<Object,Object[]> xr = ((DataEntryTable)getTableX()).createTableDataSource(dataSet, false);
			for (Entry<Object, Object[]> entryX : xr.entrySet()) {
				((DataEntryTable)getTableX()).addNewItem(entryX.getKey(), entryX.getValue());
			}
		}
	}

	public AbstractField getSource() {
		return source;
	}

	public void setSource(AbstractField source) {
		this.source = source;
	}

}
